import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import { BaseEntity } from '../common/base/base.entity';
import { User } from './user.entity';
import { OrderItem } from './order-item.entity';

@Entity('order')
export class Order extends BaseEntity {
  @Column({
    type: 'varchar',
    length: 32,
    unique: true,
    comment: '订单号',
  })
  orderNo: string;

  @Column({
    type: 'bigint',
    comment: '用户ID',
  })
  userId: string;

  @Column({
    type: 'enum',
    enum: ['product', 'membership', 'document'],
    comment: '订单类型',
  })
  type: 'product' | 'membership' | 'document';

  @Column({
    type: 'decimal', //
    precision: 10, //
    scale: 2, //
    comment: '订单总金额',
  })
  totalAmount: number;

  @Column({
    type: 'decimal',
    precision: 10,
    scale: 2,
    default: 0,
    comment: '优惠金额',
  })
  discountAmount: number;

  @Column({
    type: 'decimal',
    precision: 10,
    scale: 2,
    comment: '实付金额',
  })
  actualAmount: number;

  @Column({
    type: 'enum',
    enum: ['pending', 'paid', 'cancelled', 'refunded', 'closed'],
    default: 'pending',
    comment: '订单状态',
  })
  status: 'pending' | 'paid' | 'cancelled' | 'refunded' | 'closed';

  @Column({
    type: 'enum',
    enum: ['alipay', 'wechat'],
    nullable: true,
    comment: '支付方式',
  })
  paymentMethod?: 'alipay' | 'wechat';

  @Column({
    type: 'varchar',
    length: 64,
    nullable: true,
    comment: '支付流水号',
  })
  paymentNo?: string;

  @Column({
    type: 'timestamp',
    nullable: true,
    comment: '支付时间',
  })
  paidAt?: Date;

  @Column({
    type: 'timestamp',
    nullable: true,
    comment: '取消时间',
  })
  cancelledAt?: Date;

  @Column({
    type: 'varchar',
    length: 500,
    nullable: true,
    comment: '取消原因',
  })
  cancelReason?: string;

  @Column({
    type: 'timestamp',
    nullable: true,
    comment: '订单过期时间',
  })
  expireAt?: Date;

  @Column({
    type: 'timestamp',
    nullable: true,
    comment: '订单完成时间',
  })
  closedAt?: Date;

  @Column({
    type: 'decimal',
    precision: 10,
    scale: 2,
    nullable: true,
    comment: '退款金额',
  })
  refundAmount?: number;

  @Column({
    type: 'varchar',
    length: 500,
    nullable: true,
    comment: '退款原因',
  })
  refundReason?: string;

  @Column({
    type: 'timestamp',
    nullable: true,
    comment: '退款时间',
  })
  refundedAt?: Date;

  // 关联
  @ManyToOne(() => User)
  @JoinColumn({ name: 'userId' })
  user: User;

  @OneToMany(() => OrderItem, (item) => item.order)
  items: OrderItem[];
}
